<template>
	<view class="info">
		<scroll-view class="info-list-scroll" scroll-y style="height: 100%" @scrolltolower="load">
			<view class="info-list">
				<view v-for="m in messages" :key="m.id" class="info-list-item" @click="deleteMsg(m)">
					<info-card
						:options="{
							avatar: m.author.username[0],
							username: m.author.username,
							time: m.date,
							content: m.content
						}"
					/>
				</view>
			</view>
		</scroll-view>
		<view class="info-add">
			<editor id="editor" class="info-add-edit" show-img-size show-img-toolbar show-img-resize placeholder="写下你的服务心得..." @input="changeEditor" />
			<el-button type="primary" style="float:right;margin-top: 20px" @click="publish">发表</el-button>
		</view>
	</view>
</template>

<script>
import { mapMutations, mapState } from 'vuex';
import InformationCard from '../../../components/information-card/index';

export default {
	name: 'index',
	components: { InfoCard: InformationCard },
	data() {
		return {
			messages: [],
			editorContent: ''
		};
	},
	computed: {
		...mapState('user', ['userInfo'])
	},
	mounted: function() {
		this.getList();
	},
	methods: {
		getList() {
			this.$request('system/chat/list').then(res => {
				console.log(res);
				this.messages = res.data;
			});
		},
		load() {
			this.getList();
		},
		publish() {
			let now = new Date();
			let nowFormatter = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
			let o = {
				content: this.editorContent,
				author: this.userInfo
			};
			this.$request('system/chat/add', o).then(res => {
				if (res.id) this.$message.success('发表成功');
				else this.$message.error('发表失败');
				this.getList();
			});
		},
		changeEditor({ detail: { html, text, delta } }) {
			this.editorContent = html;
		},
		deleteMsg(msg) {
			let that = this;
			if (that.userInfo.username === 'admin' || that.userInfo._id === msg.author._id) {
				that.$alert('确认删除此条消息？', '删除后将不可恢复', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(res => {
					that.$request('system/chat/deleteMsg', {
						user_id: that.userInfo._id,
						msg_id: msg._id
					}).then(res => {
						that.msgSuccess('删除成功');
						that.getList();
					});
				});
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.info {
	display: flex;

	&-list-scroll {
		flex: 6;
	}

	&-list {
		padding: 0;
		margin: 0;
		display: grid;
		grid-template-columns: 1fr 1fr;
	}

	&-add {
		flex: 4;
		//background-color: #f00;
		padding: 50px;
		box-sizing: border-box;

		&-edit {
			border-radius: 10px;
			padding: 10px;
			box-sizing: border-box;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
		}
	}
}
</style>
